<template>
  <div v-loading="loading" class="grade" element-loading-text="加载中...">
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="onOpenAddField"> 添加字段 </HPlainButton>

        <!-- 批量操作按钮 -->
        <el-dropdown trigger="click">
          <HButton :disabled="disableBatchBtn">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(false)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(true)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="onDelBatchField">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 搜索条件 -->
      <div class="search flex-align-center">
        <el-input
          v-model.trim="listFieldSearch.name"
          placeholder="字段名称"
          class="input-width"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <!-- 列表表样 -->
    <div class="table-grade">
      <el-table
        ref="fieldTable"
        border
        stripe
        resizable
        :data="fieldData"
        height="100%"
        style="position: absolute"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column show-overflow-tooltip prop="name" label="字段名称" width="120" />
        <el-table-column show-overflow-tooltip prop="type" label="字段类型" width="120">
          <template #default="scope">
            <span>
              {{
                scope.row.type == 1
                  ? '文本'
                  : scope.row.type == 2
                  ? '多行文本'
                  : scope.row.type == 3
                  ? '单选'
                  : scope.row.type == 4
                  ? '多选'
                  : scope.row.type == 5
                  ? '多图'
                  : scope.row.type == 6
                  ? '附件'
                  : '视频'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="字段内容" />
        <el-table-column show-overflow-tooltip prop="tip" label="字段提示" />
        <el-table-column label="移动端显示" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px">
              <el-switch v-model="scope.row.mobileShow" disabled />
              <span v-if="scope.row.mibileShow">显示</span>
              <span v-else>隐藏</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="required" label="是否必填" width="120">
          <template #default="scope">
            <span>
              {{ scope.row.required == true ? '必填' : '可填' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="onOpenEditField(scope.row)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagingtion"
        :list_total="fieldTotal"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
    <!-- 添加/编辑  字段弹窗 -->
    <SelfDefined
      :title="fieldTitle"
      :is-open="networkFieldDialog"
      :field-vo="networkFieldVo"
      @on-delete="delNetworkFieldApi($event)"
      @on-save="saveApi($event)"
      @on-close="networkFieldDialog = false"
    >
    </SelfDefined>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  // 引入
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  import {
    getnetworkSerList,
    saveNetworkField,
    batchDisableNetworkField,
    deleteNetworkField,
    getServiceInfo,
  } from '@/api/network'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'

  const disableBatchBtn = ref(true) // 是否禁用批量操作按钮，默认禁用
  const loading = ref(false) // 加载动画
  const fieldLoading = ref(false) // 保存字段加载动画
  const listFieldSearch = ref({
    // 搜索条件
    page: 1,
    limit: 50,
    name: '',
  })
  // 字段对象
  const networkFieldVo = ref({
    id: '',
    name: '',
    type: 1,
    required: false,
    status: false,
    tip: '请输入',
    uploadQty: 1,
    uploadSize: 100,
    mobileShow: true, // 是否移动端显示 false-不显示，true-是,示例值(true)
    contents: [{ id: '', val: '' }], // 单选/多选内容
    delContentIds: [], // 删除的单选/多选内容ID
  })
  const networkFieldDialog = ref(false) // 字段弹窗
  const fieldTitle = ref('') // 新增/修改字段弹窗
  const fieldTotal = ref() // 总数目
  const fieldData = ref([]) // 表格数据
  const fieldTable = ref() // 表格dom
  const pagingtion = ref() // 分页Dom
  const selectFieldIds = ref([]) // 列表选中的字段ID
  // 列表选中列事件
  const handleChange = (val: any[]) => {
    selectFieldIds.value = []
    val.forEach((item) => {
      selectFieldIds.value.push(item.id)
    })
  }

  // 清除列表选中列事件
  const clearTableSelection = () => {
    fieldTable.value.clearSelection()
    selectFieldIds.value = []
  }

  // 初始化字段值
  const initField = () => {
    networkFieldVo.value = {
      id: '',
      name: '',
      type: 1,
      required: false,
      status: false,
      tip: '请输入',
      uploadQty: 1,
      uploadSize: 100,
      mobileShow: true,
      contents: [{ id: '', val: '' }],
      delContentIds: [],
    }
  }

  // 打开新增字段弹窗
  const onOpenAddField = () => {
    networkFieldDialog.value = true
    fieldTitle.value = '添加网点字段'
    initField()
  }

  // 打开编辑字段弹窗
  const onOpenEditField = async (obj: any) => {
    fieldTitle.value = '编辑网点字段'
    initField()
    fieldLoading.value = true
    await getServiceInfo(obj.id).then((res) => {
      fieldLoading.value = false
      networkFieldVo.value = res.data.data.row
      networkFieldDialog.value = true
    })
  }

  // 批量启用或禁用字段状态
  const updateBatchNetworkFieldStatus = (status: boolean) => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Warning),
      message: `是否 ${status ? '禁用' : '启用'} 选中的 ${selectFieldIds.value.length} 项? ${
        status ? '禁用后将不可被其他应用关联使用' : '启用后将被其他应用关联使用'
      }`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: `${status ? '确认禁用' : '确认启用'}`,
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = `${status ? '禁用' : '启用'}中...`
          setTimeout(() => {
            done()
            updateNetworkFieldStatusApi(status)
            instance.confirmButtonLoading = false
          }, 100)
        } else {
          done()
        }
      },
    }).catch(() => {
      //
    })
  }

  // 批量删除字段
  const onDelBatchField = () => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Delete),
      message: `是否删除选中的 ${selectFieldIds.value.length} 项? 删除后将不可恢复`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          setTimeout(() => {
            done()
            delNetworkFieldApi(selectFieldIds.value)
            instance.confirmButtonLoading = false
          }, 100)
        } else {
          done()
        }
      },
    }).catch(() => {})
  }

  // 请求启用或禁用字段状态
  const updateNetworkFieldStatusApi = (status: boolean) => {
    batchDisableNetworkField(selectFieldIds.value, status).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求删除字段Api
  const delNetworkFieldApi = async (arr) => {
    await deleteNetworkField(arr).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        networkFieldDialog.value = false
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求保存字段Api
  const saveApi = async (e) => {
    networkFieldVo.value = e
    fieldLoading.value = true
    await saveNetworkField(networkFieldVo.value).then((res) => {
      fieldLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        networkFieldDialog.value = false
        initField()
        getList()
      }
    })
  }

  // 请求列表数据Api
  const getList = async () => {
    loading.value = true
    listFieldSearch.value.page = pagingtion.value.current
    listFieldSearch.value.limit = pagingtion.value.size
    await getnetworkSerList(listFieldSearch.value).then((res) => {
      loading.value = false
      fieldData.value = res.data.data.rows
      fieldTotal.value = parseInt(res.data.data.total)
    })
  }

  // 监听列表选中的字段
  watch(
    () => selectFieldIds.value,
    () => {
      disableBatchBtn.value = true
      if (selectFieldIds.value.length > 0) {
        disableBatchBtn.value = false
      }
    },
  )

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
